//
//  XYLBaseRequest.m
//  AFNet-3.0
//
//  Created by 夏玉林 on 16/7/11.
//  Copyright © 2016年 夏玉林. All rights reserved.
//

#import "XYLBaseRequest.h"


@interface XYLBaseRequest ()


@end

@implementation XYLBaseRequest

+ (XYLBaseRequest *)RequestGlobal{
    static dispatch_once_t onceTocken ;
    
    static  XYLBaseRequest *obj;
    //这个GCD里面的代码只运行一次
    dispatch_once(&onceTocken, ^{
        if (!obj) {
            obj = [[XYLBaseRequest alloc] init];
        }
    });
    return obj;

}

/*
 *  检查是否有网络
 */
- (void )CheckNetStatus{
    AFNetworkReachabilityManager *managerStatus = [AFNetworkReachabilityManager sharedManager];
    //开始检测网络
    [managerStatus startMonitoring];
    
    [managerStatus setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
           
            [self showToast:@"网络异常,请检查网络设置" withDuration:1.5];
           
        }else if(status == AFNetworkReachabilityStatusReachableViaWWAN){
            [self showToast:@"欢迎来到没有wifi的世界" withDuration:1.5];
            
        }else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            
        }
    }];
    //停止检测网络
    [managerStatus stopMonitoring];
    
   
}

//拼接参数
-(NSString *)doWithParams:(NSDictionary *)paramDic{
    
    NSMutableArray *newArr = [NSMutableArray new];
    
    //@{@"username":@"sz1513",@"password":@"1234"} ->   username=sz1513&password=1234
    for (NSString *key in paramDic) {
        //拼接数组当中储存的每一个字符串元素
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,paramDic[key]];
        [newArr addObject:str];
        
    }
    //最终拼接完成的字符串
    return  [newArr componentsJoinedByString:@"&"];
    
}

- (NSString *)getCurrentDeviceLanguage{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    
    if (IOS9_DEVICE)
    {
        if ([preferredLang hasPrefix:@"zh-Hans"])
        {
            return @"zh-Hans";
        }
        else if ([preferredLang hasPrefix:@"zh-Hant"] || [preferredLang hasPrefix:@"zh-HK"] || [preferredLang hasPrefix:@"zh-TW"])
        {
            return @"zh-Hant";
        }
        else if ([preferredLang hasPrefix:@"tr"])
        {
            return @"tr";
        }
        else if ([preferredLang hasPrefix:@"es-"])
        {
            return @"es";
        }
        else
        {
            return @"en";
        }
    }
    else
    {
        return preferredLang;
    }

}

/*
 *  获取当前系统语言
 */
- (NSString *)stringWithSystemLanguageForAPI{
    NSString* preferredLang = [self getCurrentDeviceLanguage];
    
    if ([preferredLang isEqualToString:@"zh-Hans"])
    {
        return @"zh-cn";
    }
    else if([preferredLang isEqualToString:@"zh-Hant"])
    {
        return @"zh-hk";
    }
    else if ([preferredLang isEqualToString:@"tr"])
    {
        return @"tr-tr";
    }
    else if ([preferredLang isEqualToString:@"es"])
    {
        return @"es-es";
    }
    else
    {
        return @"en-us";
    }

}

/*
 *  Get请求
 */
-(void)GetRequesetWithURL:(NSString *)url andParameters:(NSDictionary *)parameters completion:(returnBlockType)block{
    
    //进行网络状态检查
    [self CheckNetStatus];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //请求二进制数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //超时操作设定
    manager.requestSerializer.timeoutInterval = 10;
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *sysStr = [NSString stringWithFormat:@"IOS|%@",[[UIDevice currentDevice] systemVersion]];
    NSString *headerStr = [NSString stringWithFormat:@"sys:%@,app:%@",sysStr,appCurVersion];
    [manager.requestSerializer setValue:headerStr forHTTPHeaderField:@"X-Heyhou-Header"];
    
    // 终止请求
    [manager.operationQueue cancelAllOperations];
    
#if 0
    /*
     *   给系统当前的的类添加一个方法， 判断app当前国家语言
     */
    [manager.requestSerializer setValue:[NSString stringWithSystemLanguageForAPI] forHTTPHeaderField:@"Accept-Language"];
    
#endif
    
#pragma mark======多国语言配置===========
    
#if 1
    /*
     *   给系统当前的的类添加一个方法， 判断app当前国家语言
     */
    [manager.requestSerializer setValue:[self stringWithSystemLanguageForAPI] forHTTPHeaderField:@"Accept-Language"];
    
#endif
    
    
    [XYLToastView showToast:@"加载中..." withDuration:1.5];
    //[[ProgressBox GlobalManager] loading:@"加载中..."];
    
    [manager GET:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"请求到的数据%@",dic);
       [XYLToastView dismissToast];
        
        //请求成功
        block(nil,dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        [XYLToastView dismissToast];
        
        block(error,nil);
    }];
}

/*
 *  Post请求
 */
- (void)PostRequestWithURL:(NSString *)url andParams:(NSDictionary *)parameters completion:(returnBlockType)block{

    //进行网络状态检查
    [self CheckNetStatus];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //请求二进制数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //超时操作设定
    manager.requestSerializer.timeoutInterval = 10;
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *sysStr = [NSString stringWithFormat:@"IOS|%@",[[UIDevice currentDevice] systemVersion]];
    NSString *headerStr = [NSString stringWithFormat:@"sys:%@,app:%@",sysStr,appCurVersion];
    [manager.requestSerializer setValue:headerStr forHTTPHeaderField:@"X-Heyhou-Header"];
    
    // 终止请求
    [manager.operationQueue cancelAllOperations];
    
#if 0
    /*
     *   给系统当前的的类添加一个方法， 判断app当前国家语言
     */
   [manager.requestSerializer setValue:[NSString stringWithSystemLanguageForAPI] forHTTPHeaderField:@"Accept-Language"];
    
#endif

#pragma mark======多国语言配置===========
    
#if 0
    /*
     *   给系统当前的的类添加一个方法， 判断app当前国家语言
     */
    [manager.requestSerializer setValue:[self stringWithSystemLanguageForAPI] forHTTPHeaderField:@"Accept-Language"];
    
#endif

  [XYLToastView showToast:@"加载中..." withDuration:1.5];
    
  [manager POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
      
      //请求失败
   //   [XYLToastView dismissToast];
      
    //  NSLog(@"请求到的数据%@",dic);
      
      //请求成功
      block(nil,dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        
        //请求失败
   //     [XYLToastView dismissToast];
        
        block(error,nil);
    }];
    
}

/*
 *   停止所有网络请求
 */

+ (void)cancelAllOperation{
    [[AFHTTPSessionManager manager].operationQueue cancelAllOperations];
}


/*
 *   参数拼接方法
 */
- (NSDictionary *)DictWithFunction:(NSString *)functionName AndWithparma:(NSString *)string{
    
    /*
     *   参数拼接
     */
    
    NSDictionary *dic = @{@"uid":[NSString stringWithFormat:@"%@",functionName],@"token":[NSString stringWithFormat:@"%@",string]};
    
  //  NSDictionary *dic =@{@"class":@"AppInterface",@"function":[NSString stringWithFormat:@"%@",functionName],@"params":[NSString stringWithFormat:@"%@",string]};
                                                                                      
                                                                                      
    return dic;
}
/*
 *  展示网络检查状态的方法
 */
- (void)showToast:(NSString *)message withDuration:(NSUInteger)duration {
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.text = message;
        toast.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.tag = 1024;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];
        toast.layer.cornerRadius = kCBToastCornerRadius;
        toast.layer.masksToBounds = YES;
        
        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //adjust the label to the new height
        CGRect newFrame = toast.frame;
        newFrame.size = CGSizeMake(expectedLabelSize.width + kCBToastPadding,
                                   expectedLabelSize.height + kCBToastPadding);
        toast.frame = newFrame;
        
        // add the toast to the root window (so it overlays everything)
        if ([toast.text length] > 0) {
            [FLT_APP_WINDOW addSubview:toast];
            
            // get the window frame to determine placement
            CGRect windowFrame = FLT_APP_WINDOW.frame;
            
            // align the toast properly
            toast.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);
            
            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toast.frame = CGRectMake(round(toast.frame.origin.x),
                                     round(toast.frame.origin.y),
                                     toast.frame.size.width,
                                     toast.frame.size.height);
            
            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            
            // values being aninmated
            toast.alpha = 1.0f;
            
            // perform the animation
            [UIView commitAnimations];
            
            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = duration;
            
            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toast];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
            
            // values being animated
            toast.alpha = 0.0f;
            
            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}



-(void)dealloc{
    NSLog(@"销毁%@",self);
}

@end
